import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login1")
public class login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 读取请求
        req.setCharacterEncoding("utf8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        // 验证用户名密码
        if (!"zhangsan".equals(name) || !"123".equals(password)) {
            // 登录失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误！！");
            return;
        }

        // 验证完成之后创建 cookie 创建会话
        // 这里设置 true 是为了 如果不存在 这个会话 的话就 重新创建一个
        HttpSession session= req.getSession(true);
        session.setAttribute("name",name);
        session.setAttribute("password",password);
        session.setAttribute("TimeMillis",System.currentTimeMillis());

        // 创建完 会话之后，登录成功 跳转网页
        resp.sendRedirect("index1");
    }
}
